/*
ONEGAME
Copyright (C) 2009  Pablo Caballero

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package one.main;

import java.awt.Container;
import java.awt.Graphics;
import java.awt.Window;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import one.project.FactoryProject;
import one.project.IProject;


/**
 * Main Panel
 * @author Pablo Caballero
 * @version 1.0 16-jun-2009
 */
public class MainPanel extends javax.swing.JPanel {

	protected IProject project;

	/** Creates new form MainPanel */
	public MainPanel() {
		initComponents();
		setProject(FactoryProject.getProject());
                toolPanel.setMapPanel(mapPanel);
	}

	/**
	 * Exits from the application
	 * @param status exit status
	 * @see java.lang.System#exit(int) 
	 */
	public void exit(int status) {
		System.exit(status);
	}

	/**
	 * Gets the main menu
	 * @return the main menu
	 */
	public javax.swing.JMenuBar getMainMenu() {
		return mainMenu;
	}

	@Override
	public void paint(Graphics g) {
		//Posiciona el cargando en su sitio
		if (this.getWidth() - 25 != lmgLoading.getX() || this.getHeight() - 25 != lmgLoading.getY()) {
			lmgLoading.setLocation(this.getWidth() - 25, this.getHeight() - 25);
		}
		super.paint(g);
	}

	/**
	 * Gets the current project
	 * @return the current project
	 */
	public IProject getProject() {
		return project;
	}

	/**
	 * Sets the current project and updates the system
	 * @param project
	 */
	public void setProject(IProject project) {
		this.project = project;
		toolPanel.setProject(project);
		mapPanel.setProject(project);
	}

	/**
	 * Creates a new project
	 */
	protected void newProject() {
		setProject(FactoryProject.getProject());
	}

	/**
	 * Opens the project
	 */
	protected void openProject() {
		int res;
		try {
			newProject();
			projectFileChooser.setFileFilter(project.getFileFilter());
			do {
				res = projectFileChooser.showOpenDialog(this);
			} while (res == JFileChooser.APPROVE_OPTION && !projectFileChooser.getSelectedFile().exists());
			if (res == JFileChooser.APPROVE_OPTION && projectFileChooser.getSelectedFile().exists()) {
				project.setPath(projectFileChooser.getSelectedFile().toURI());
				project.load();
			}
		} catch (Exception ex) {
			Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	/**
	 * Saves the project
	 */
	protected void saveAsProject() {
		int res;
		boolean exists;

		try {
			if (getProject().getPath() == null) {
				projectFileChooser.setFileFilter(project.getFileFilter());
				res = projectFileChooser.showSaveDialog(this);

				if (res == JFileChooser.APPROVE_OPTION) {
					exists = projectFileChooser.getSelectedFile().exists();
					if (!exists || (exists && SystemMessage.showConfirmDialog(this, "PROJECT_FILE_SAVE_CONFIRMATION") == JOptionPane.OK_OPTION)) {// NOI18N
						project.setPath(projectFileChooser.getSelectedFile().toURI());
						project.save();
					}
				}
			} else {
				project.save();
			}
		} catch (Exception ex) {
			Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	/**
	 * Saves the current project as another project
	 */
	protected void saveProject() {
		if (getProject().getPath() != null) {
			try {
				project.save();
			} catch (Exception ex) {
				Logger.getLogger(MainPanel.class.getName()).log(Level.SEVERE, null, ex);
			}
		} else {
			saveAsProject();
		}
	}

	/**
	 * Shows the about dialog
	 */
	private void aboutProject() {
		Container window = SwingUtilities.getAncestorOfClass(Window.class, this);
		AboutDlg about = new AboutDlg(window != null ? (Window) window : null);
		about.setVisible(true);
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainMenu = new javax.swing.JMenuBar();
        mnFile = new javax.swing.JMenu();
        mnItmNewProject = new javax.swing.JMenuItem();
        mnItmOpenProject = new javax.swing.JMenuItem();
        sepFile1 = new javax.swing.JSeparator();
        mnItmSaveProject = new javax.swing.JMenuItem();
        mnItmSaveAsProject = new javax.swing.JMenuItem();
        sepFile2 = new javax.swing.JSeparator();
        mnItmExit = new javax.swing.JMenuItem();
        mnEdit = new javax.swing.JMenu();
        mnView = new javax.swing.JMenu();
        mnMode = new javax.swing.JMenu();
        mnDraw = new javax.swing.JMenu();
        mnScale = new javax.swing.JMenu();
        mnTools = new javax.swing.JMenu();
        mnGame = new javax.swing.JMenu();
        mnHelp = new javax.swing.JMenu();
        mnItmAbout = new javax.swing.JMenuItem();
        projectFileChooser = new javax.swing.JFileChooser();
        upPanel = new javax.swing.JPanel();
        spCentral = new javax.swing.JSplitPane();
        pnlTools = new javax.swing.JPanel();
        spTools = new javax.swing.JSplitPane();
        charactersMapPanel = new one.main.CharactersMapPanel();
        toolPanel = new one.tool.ToolPanel();
        mapPanel = new one.main.MapPanel();
        lmgLoading = new javax.swing.JLabel();

        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("one/language/labels"); // NOI18N
        mnFile.setText(bundle.getString("MAINMENU_FILE")); // NOI18N

        mnItmNewProject.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_N, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mnItmNewProject.setText(bundle.getString("MAINMENU_NEW_PROJECT")); // NOI18N
        mnItmNewProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnItmNewProjectActionPerformed(evt);
            }
        });
        mnFile.add(mnItmNewProject);

        mnItmOpenProject.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_O, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mnItmOpenProject.setText(bundle.getString("MAINMENU_OPEN_PROJECT")); // NOI18N
        mnItmOpenProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnItmOpenProjectActionPerformed(evt);
            }
        });
        mnFile.add(mnItmOpenProject);
        mnFile.add(sepFile1);

        mnItmSaveProject.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.CTRL_MASK));
        mnItmSaveProject.setText(bundle.getString("MAINMENU_SAVE_PROJECT")); // NOI18N
        mnItmSaveProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnItmSaveProjectActionPerformed(evt);
            }
        });
        mnFile.add(mnItmSaveProject);

        mnItmSaveAsProject.setAccelerator(javax.swing.KeyStroke.getKeyStroke(java.awt.event.KeyEvent.VK_S, java.awt.event.InputEvent.SHIFT_MASK | java.awt.event.InputEvent.CTRL_MASK));
        mnItmSaveAsProject.setText(bundle.getString("MAINMENU_SAVEAS_PROJECT")); // NOI18N
        mnItmSaveAsProject.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnItmSaveAsProjectActionPerformed(evt);
            }
        });
        mnFile.add(mnItmSaveAsProject);
        mnFile.add(sepFile2);

        mnItmExit.setText(bundle.getString("MAINMENU_EXIT")); // NOI18N
        mnItmExit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnItmExitActionPerformed(evt);
            }
        });
        mnFile.add(mnItmExit);

        mainMenu.add(mnFile);

        mnEdit.setText(bundle.getString("MAINMENU_EDIT")); // NOI18N
        mnEdit.setEnabled(false);
        mainMenu.add(mnEdit);

        mnView.setText(bundle.getString("MAINMENU_VIEW")); // NOI18N
        mnView.setEnabled(false);
        mainMenu.add(mnView);

        mnMode.setText(bundle.getString("MAINMENU_MODE")); // NOI18N
        mnMode.setEnabled(false);
        mainMenu.add(mnMode);

        mnDraw.setText(bundle.getString("MAINMENU_DRAW")); // NOI18N
        mnDraw.setEnabled(false);
        mainMenu.add(mnDraw);

        mnScale.setText(bundle.getString("MAINMENU_SCALE")); // NOI18N
        mnScale.setEnabled(false);
        mainMenu.add(mnScale);

        mnTools.setText(bundle.getString("MAINMENU_TOOLS")); // NOI18N
        mnTools.setEnabled(false);
        mainMenu.add(mnTools);

        mnGame.setText(bundle.getString("MAINMENU_GAME")); // NOI18N
        mnGame.setEnabled(false);
        mainMenu.add(mnGame);

        mnHelp.setText(bundle.getString("MAINMENU_HELP")); // NOI18N

        mnItmAbout.setText(bundle.getString("MAINMENU_ABOUT")); // NOI18N
        mnItmAbout.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mnItmAboutActionPerformed(evt);
            }
        });
        mnHelp.add(mnItmAbout);

        mainMenu.add(mnHelp);

        upPanel.setLayout(new javax.swing.BoxLayout(upPanel, javax.swing.BoxLayout.LINE_AXIS));

        spCentral.setResizeWeight(0.1);

        pnlTools.setLayout(new javax.swing.BoxLayout(pnlTools, javax.swing.BoxLayout.LINE_AXIS));

        spTools.setDividerSize(7);
        spTools.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        spTools.setResizeWeight(0.7);
        spTools.setOneTouchExpandable(true);

        javax.swing.GroupLayout charactersMapPanelLayout = new javax.swing.GroupLayout(charactersMapPanel);
        charactersMapPanel.setLayout(charactersMapPanelLayout);
        charactersMapPanelLayout.setHorizontalGroup(
            charactersMapPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 54, Short.MAX_VALUE)
        );
        charactersMapPanelLayout.setVerticalGroup(
            charactersMapPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 190, Short.MAX_VALUE)
        );

        spTools.setLeftComponent(charactersMapPanel);
        spTools.setRightComponent(toolPanel);

        pnlTools.add(spTools);

        spCentral.setLeftComponent(pnlTools);

        javax.swing.GroupLayout mapPanelLayout = new javax.swing.GroupLayout(mapPanel);
        mapPanel.setLayout(mapPanelLayout);
        mapPanelLayout.setHorizontalGroup(
            mapPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 284, Short.MAX_VALUE)
        );
        mapPanelLayout.setVerticalGroup(
            mapPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 304, Short.MAX_VALUE)
        );

        spCentral.setRightComponent(mapPanel);

        upPanel.add(spCentral);

        lmgLoading.setIcon(new javax.swing.ImageIcon(getClass().getResource("/one/image/loading.gif"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(upPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 347, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(292, Short.MAX_VALUE)
                .addComponent(lmgLoading)
                .addGap(30, 30, 30))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(upPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)
                .addGap(3, 3, 3)
                .addComponent(lmgLoading))
        );
    }// </editor-fold>//GEN-END:initComponents

	private void mnItmExitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnItmExitActionPerformed
		exit(0);
	}//GEN-LAST:event_mnItmExitActionPerformed

	private void mnItmOpenProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnItmOpenProjectActionPerformed
		openProject();
	}//GEN-LAST:event_mnItmOpenProjectActionPerformed

	private void mnItmSaveProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnItmSaveProjectActionPerformed
		saveProject();
	}//GEN-LAST:event_mnItmSaveProjectActionPerformed

	private void mnItmSaveAsProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnItmSaveAsProjectActionPerformed
		saveAsProject();
	}//GEN-LAST:event_mnItmSaveAsProjectActionPerformed

	private void mnItmNewProjectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnItmNewProjectActionPerformed
		newProject();
	}//GEN-LAST:event_mnItmNewProjectActionPerformed

	private void mnItmAboutActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mnItmAboutActionPerformed
		aboutProject();
	}//GEN-LAST:event_mnItmAboutActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private one.main.CharactersMapPanel charactersMapPanel;
    private javax.swing.JLabel lmgLoading;
    private javax.swing.JMenuBar mainMenu;
    private one.main.MapPanel mapPanel;
    private javax.swing.JMenu mnDraw;
    private javax.swing.JMenu mnEdit;
    private javax.swing.JMenu mnFile;
    private javax.swing.JMenu mnGame;
    private javax.swing.JMenu mnHelp;
    private javax.swing.JMenuItem mnItmAbout;
    private javax.swing.JMenuItem mnItmExit;
    private javax.swing.JMenuItem mnItmNewProject;
    private javax.swing.JMenuItem mnItmOpenProject;
    private javax.swing.JMenuItem mnItmSaveAsProject;
    private javax.swing.JMenuItem mnItmSaveProject;
    private javax.swing.JMenu mnMode;
    private javax.swing.JMenu mnScale;
    private javax.swing.JMenu mnTools;
    private javax.swing.JMenu mnView;
    private javax.swing.JPanel pnlTools;
    private javax.swing.JFileChooser projectFileChooser;
    private javax.swing.JSeparator sepFile1;
    private javax.swing.JSeparator sepFile2;
    private javax.swing.JSplitPane spCentral;
    private javax.swing.JSplitPane spTools;
    private one.tool.ToolPanel toolPanel;
    private javax.swing.JPanel upPanel;
    // End of variables declaration//GEN-END:variables
}
